using System;
using System.Collections.Generic;
using CMS_Admin.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CMS_Admin.Backend.Api.ParamModel;
using Newtonsoft.Json;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;

namespace CMS_Admin.Backend.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    // [Authorize]
    [ApiController]
    [Route("role")]
    public class RoleController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private IRepository<Roles> _userRoles;
        private IRepository<Jurisdiction> _jurisdiction;
        private IRepository<RolesJurisdiction> _rolesJurisdiction;

        private readonly IConfiguration _configuration;

        public RoleController(IConfiguration configuration, IRepository<Users> usersRespository, IRepository<Roles> userRoles, IRepository<Jurisdiction> jurisdiction, IRepository<RolesJurisdiction> rolesJurisdiction)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _userRoles = userRoles;
            _rolesJurisdiction = rolesJurisdiction;
            _jurisdiction = jurisdiction;

        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {//get请求默认从uri从获取参数，所以此处应该加上FromQuery的特性才能正确获得参数
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;




            // 获得所有满足条件的记录
            // var users = _usersRespository.Table.Where(x => x.IsDeleted == false);

            var rolesjurisdiction = from roleJurisdiction in _rolesJurisdiction.Table
                                    join roles in _userRoles.Table on roleJurisdiction.RolesId equals roles.Id
                                    join jurisdiction in _jurisdiction.Table on roleJurisdiction.JurisdictionId equals jurisdiction.Id
                                    orderby roleJurisdiction.Id
                                    where roles.IsDeleted == false
                                    select new
                                    {

                                        Id = roles.Id,
                                        RoleName = roles.RoleName,
                                        CreatedTime = roleJurisdiction.CreatedTime,
                                        IsActived = roles.IsActived,
                                        IsDeleted = roles.IsDeleted,
                                        jurisdictionName = jurisdiction.JurisdictionName

                                    };


            // 对获得的记录分页
            var u = rolesjurisdiction.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res = new
            {
                Code = 200,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = rolesjurisdiction.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }

        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("jurisdiction")]
        public dynamic Get()
        {
            var list = _jurisdiction.Table.ToList();


            return new
            {
                Code = 200,
                Data = list,
                Msg = "获取用户权限列表成功^_^"
            };

        }
        /// <summary>
        /// 创建角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public string Post(NewJurisdiction model)
        {


            var rolesName = model.RoleName;

            var newrole = _userRoles.Table.Where(ur => ur.RoleName == rolesName).FirstOrDefault();

            if (newrole != null)
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "该角色已存在，请重试"
                };
                return JsonHelper.Serialize(tmp);
            }

            var jurisdictionName = model.JurisdictionName;
            // var rolesId = model.RolesId;

            var juid = _jurisdiction.Table.Where(j => j.JurisdictionName == jurisdictionName).FirstOrDefault()?.Id;
            var jurisdictionId = juid;
            if (string.IsNullOrEmpty(rolesName))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "权限名不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);

            };



            var roles = new Roles
            {

                RoleName = rolesName,


            };

            _userRoles.Insert(roles);





            var rj = new RolesJurisdiction
            {
                Jurisdiction = _jurisdiction.Table.Single(j => j.Id == jurisdictionId),
                Roles = _userRoles.Table.Single(r => r.Id == roles.Id)

            };

            _rolesJurisdiction.Insert(rj);



            var res = new
            {
                Code = 200,
                Data = new
                {
                    roles,
                    jurisdictionName = model.JurisdictionName
                },
                Msg = "添加角色成功"
            };
            return JsonHelper.Serialize(res);


        }






        /// <summary>
        /// 修改指定权限冻结或删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public dynamic Put(int id, NewJurisdiction model)
        {
            var roles = _userRoles.GetById(id);

            if (roles != null)
            {
                // roles.RoleName = model.RoleName;
                roles.IsActived = model.IsActived;
                roles.IsDeleted = model.IsDeleted;


                roles.UpdatedTime = DateTime.Now;
                _userRoles.Update(roles);

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = roles,
                    Msg = string.Format("你修改的权限的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }
    }

}